package com.yn.common.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.springframework.web.multipart.MultipartFile;

/**
 * 二维码工具类
 */
public class QRCodeUtil {

    /**
     * 生成不带Logo的二维码Base64字符串
     *
     * @param qrCodeText 二维码内容
     * @param size       二维码尺寸
     * @return 二维码图片的Base64编码字符串
     */
    public static String generateBase64QRCode(String qrCodeText, int size) {
        return "data:image/png;base64," + generateBase64QRCode(qrCodeText, size, (String) null, 0);
    }

    /**
     * 生成带Logo的二维码Base64字符串，Logo来自OSS地址或本地文件
     *
     * @param qrCodeText 二维码内容
     * @param size       二维码尺寸
     * @param logoPath   Logo的文件路径（可以是本地路径或者OSS路径）
     * @param logoSize   Logo的尺寸
     * @return 二维码图片的Base64编码字符串
     */
    public static String generateBase64QRCodeWithLogo(String qrCodeText, int size, String logoPath, int logoSize) {
        return "data:image/png;base64," + generateBase64QRCode(qrCodeText, size, logoPath, logoSize);
    }

    /**
     * 生成带Logo的二维码Base64字符串，Logo来自OSS地址或本地文件
     *
     * @param qrCodeText 二维码内容
     * @param size       二维码尺寸
     * @param logoFile   Logo的文件
     * @param logoSize   Logo的尺寸
     * @return 二维码图片的Base64编码字符串
     */
    public static String generateBase64QRCodeWithLogo(String qrCodeText, int size, MultipartFile logoFile, int logoSize) {
        return "data:image/png;base64," + generateBase64QRCode(qrCodeText, size, logoFile, logoSize);
    }


    /**
     * 生成二维码Base64字符串的核心方法
     *
     * @param qrCodeText 二维码内容
     * @param size       二维码尺寸
     * @param logoPath   Logo的文件路径（可以为空）
     * @param logoSize   Logo的尺寸（如果logoPath为空，则不使用）
     * @return 二维码图片的Base64编码字符串
     */
    private static String generateBase64QRCode(String qrCodeText, int size, String logoPath, int logoSize) {
        try {
            Map<EncodeHintType, Object> hintMap = new HashMap<>();
            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hintMap.put(EncodeHintType.MARGIN, 0);
            hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
            // 裁剪掉二维码周围的白边
            BitMatrix trimmedMatrix = trimWhiteBorder(byteMatrix);
            MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF); // 几乎黑的二维码颜色和白色背景
            BufferedImage image = MatrixToImageWriter.toBufferedImage(trimmedMatrix, config); // 使用自定义配置生成图像

            // 如果提供了Logo的文件路径，则添加Logo
            if (logoPath != null && !logoPath.isEmpty()) {
                // 从OSS路径添加logo
                BufferedImage logo = ImageIO.read(new URL(logoPath));
                // 将Logo添加到二维码中心
                addLogoToQRCode(image, logo, logoSize);
            }

            // 将二维码写入ByteArrayOutputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            baos.close();

            // 转换为Base64
            byte[] imageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 注意这个方法依赖于ZXing库和Spring框架的一些组件
    private static String generateBase64QRCode(String qrCodeText, int size, MultipartFile logoFile, int logoSize) {
        try {
            Map<EncodeHintType, Object> hintMap = new HashMap<>();
            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hintMap.put(EncodeHintType.MARGIN, 0);  // 设置边距为0
            hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);

            // 裁剪掉二维码周围的白边
            BitMatrix trimmedMatrix = trimWhiteBorder(byteMatrix);
            MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF); // 几乎黑的二维码颜色和白色背景
            BufferedImage image = MatrixToImageWriter.toBufferedImage(trimmedMatrix, config); // 使用自定义配置生成图像

            // 如果提供了Logo的MultipartFile，则添加Logo
            if (logoFile != null && !logoFile.isEmpty()) {
                InputStream logoInputStream = logoFile.getInputStream();
                BufferedImage logo = ImageIO.read(logoInputStream);
                if (logo.getColorModel().getColorSpace().getType() != ColorSpace.TYPE_RGB) {
                    throw new IllegalArgumentException("Logo image is not in expected color space");
                }
                // 将Logo添加到二维码中心
                addLogoToQRCode(image, logo, logoSize);
            }

            // 将二维码写入ByteArrayOutputStream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            byte[] imageBytes = baos.toByteArray();
            baos.close();

            // 转换为Base64
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 裁掉白色白边
     * @param matrix
     * @return
     */
    private static BitMatrix trimWhiteBorder(BitMatrix matrix) {
        int[] enclosingRectangle = matrix.getEnclosingRectangle();
        int left = enclosingRectangle[0];
        int top = enclosingRectangle[1];
        int width = enclosingRectangle[2];
        int height = enclosingRectangle[3];

        BitMatrix trimmedMatrix = new BitMatrix(width, height);
        trimmedMatrix.clear();
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (matrix.get(x + left, y + top)) {
                    trimmedMatrix.set(x, y);
                }
            }
        }
      return trimmedMatrix;
    }

    /**
     * 将Logo添加到二维码中
     */
    private static void addLogoToQRCode(BufferedImage qrcode, BufferedImage originalLogo, int logoSize) {
        Graphics2D graphics = (Graphics2D) qrcode.getGraphics();

        // 设置渲染质量
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        // 计算Logo的目标尺寸
        int widthLogo = originalLogo.getWidth(null) > qrcode.getWidth() * 1 / 5 ? qrcode.getWidth() * 1 / 5 : originalLogo.getWidth(null);
        int heightLogo = originalLogo.getHeight(null) > qrcode.getHeight() * 1 / 5 ? qrcode.getHeight() * 1 / 5 : originalLogo.getHeight(null);

        // 如果提供了自定义大小，则使用该大小
        if (logoSize > 0) {
            widthLogo = logoSize;
            heightLogo = logoSize;
        }
        // 使用平滑缩放算法生成新的缩放后的 Logo 图像
        Image scaledLogo = originalLogo.getScaledInstance(widthLogo, heightLogo, Image.SCALE_SMOOTH);
        BufferedImage logo = new BufferedImage(widthLogo, heightLogo, BufferedImage.TYPE_INT_ARGB_PRE);
        Graphics2D g2dLogo = logo.createGraphics();
        g2dLogo.drawImage(scaledLogo, 0, 0, null);
        g2dLogo.dispose();

        // 计算Logo放置在二维码中的位置
        int x = (qrcode.getWidth() - widthLogo) / 2;
        int y = (qrcode.getHeight() - heightLogo) / 2;

        // 定义边框的大小，这里设置为2像素
        int borderSize = 2;

        // 保存当前状态
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));

        // 绘制白色边框
        graphics.setColor(Color.WHITE);
        graphics.fillRect(x - borderSize, y - borderSize, widthLogo + 2 * borderSize, heightLogo + 2 * borderSize);

        // 绘制Logo的影像
        graphics.drawImage(logo, x, y, widthLogo, heightLogo, null);

        // 恢复之前的状态
        graphics.dispose();
    }


}

